package com.jovision.sovplay;

import android.Manifest;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aviccxzx.smarthome.R;
import com.aviccxzx.smarthome.UserModule.CamMsgActivity;
import com.aviccxzx.smarthome.base.BaseActivity;
import com.aviccxzx.smarthome.entity.FeedBack;
import com.aviccxzx.smarthome.netutil.app.App;
import com.aviccxzx.smarthome.netutil.msg.MsgCenter;
import com.aviccxzx.smarthome.service.RetrofitHelper;
import com.aviccxzx.smarthome.service.RetrofitService;
import com.aviccxzx.smarthome.utils.HasAudioPermission;
import com.aviccxzx.smarthome.video.CloudUtil;
import com.jovision.AppConsts;
import com.jovision.CommonUtil;
import com.jovision.JVNetConst;
import com.jovision.JniUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.List;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.widget.Toast.makeText;
import static com.aviccxzx.smarthome.R.id.playsurface;
import static com.aviccxzx.smarthome.UserModule.MyCenterdetail.REQUEST_FILE_PERM;
import static com.jovision.AppConsts.CAPTURE_PATH;
import static com.jovision.AppConsts.VIDEO_PATH;

/**
 * Created by juyang on 16/11/15.
 */

public class JVSovPlayActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {

    private static final String TAG = "JVSovPlayActivity";

    private int window = 0;
    private String ystNum = "";//连接的设备号
    private String group = "";
    private int ystNo = 0;
    private String devUser = "";//连接的用户名
    private String devPwd = "";//连接的密码
    private boolean devAdmin;//是否是管理员

    private TextView linkState;//视频连接状态
    SurfaceView playSurface;//
    SurfaceHolder surfaceHolder;//

    private boolean isConnected = false;//是否已连接
    private RelativeLayout landscape_back;//横屏时的返回键

    private PopupWindow popupWindow;
    private ArrayAdapter<String> adapter;

    private CheckBox video_model;
    private RelativeLayout titleview;
    ImageView open_voice;
    ImageView double_call, change_screen_img, big_microphone_img, video_cut;
    String devNum = "";
    ImageView title_right_img;
    boolean hasShown = true;
    int version;//摄像机的高低版本
    /**
     * 存储器
     */
    public SharedPreferences spf;
    /**
     * 存储器默认名称
     */
    public static final String SPF_Name = "set";

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */

    static {
        System.loadLibrary("gnustl_shared");
        System.loadLibrary("stlport_shared");
        System.loadLibrary("tools");
        System.loadLibrary("nplayer");
        System.loadLibrary("alu");
        System.loadLibrary("play");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    String newpwd = "";
    AlertDialog dialog;

    protected void initSettings() {
        JniUtil.initElian();
        CloudUtil.startLanSearchServer(CommonUtil.getLocalIpAddress());
        CommonUtil.createDirectory(AppConsts.LOG_PATH);
        CommonUtil.createDirectory(AppConsts.CAPTURE_PATH);
        CommonUtil.createDirectory(AppConsts.VIDEO_PATH);
        CommonUtil.createDirectory(AppConsts.DOWNLOAD_PATH);
        try {
            JniUtil.initSDK(getApplication(), AppConsts.LOG_PATH, "");
        } catch (IOException e) {
            e.printStackTrace();
        }
        spf = getSharedPreferences(SPF_Name, Context.MODE_PRIVATE);
        devNum = getIntent().getStringExtra("devNum");
        //1.添加设备到中维服务器上
        String[] ystArray = {devNum};
        SovUtil.addYSTNOS(ystArray);
        ystNum = TextUtils.isEmpty(devNum)
                ? ystNum : devNum;
        group = CommonUtil.getGroup(ystNum);
        ystNo = CommonUtil.getYST(ystNum);
        devUser = getIntent().getStringExtra("devUser");
        devPwd = getIntent().getStringExtra("devPwd");
        devAdmin = getIntent().getBooleanExtra("devAdmin", false);
        version = getIntent().getIntExtra("version", 0);
        boolean remind = spf.getBoolean("hasRemind", false);
        if (devAdmin && devPwd.equals("admin")) {
            //如果摄像机的密码没做过修改 就直接弹框让其修改
            LinearLayout layout = (LinearLayout) LayoutInflater.from(JVSovPlayActivity.this).inflate(R.layout.change_campwd_dialog, null);
            dialog = new AlertDialog.Builder(JVSovPlayActivity.this).create();
            dialog.setCancelable(false);
            LinearLayout change_campwd_ll = (LinearLayout) layout.findViewById(R.id.change_campwd_ll);
            final EditText new_pwd = (EditText) layout.findViewById(R.id.new_pwd);
            layout.findViewById(R.id.btn_sure).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //                    if (isConnected) {
                    newpwd = new_pwd.getText().toString();
                    if (!TextUtils.isEmpty(newpwd)) {
                        SovUtil.modifyStreamUserInfo(window, "admin", newpwd);
                    } else {
                        App.getApp().showToast("请先输入新密码");
                    }
                }
            });
            layout.findViewById(R.id.btn_cancle).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //TODO
                    if (doubleCalling) {
                        stopDoubleCall();
                        Toast.makeText(JVSovPlayActivity.this, "关闭对讲", Toast.LENGTH_SHORT).show();
                    }
                    if (recording) {
                        JniUtil.stopRecord(window);
                        Toast.makeText(JVSovPlayActivity.this, "停止录像", Toast.LENGTH_SHORT).show();
                        recording = false;
                    }
                    if (enableSound) {
                        enableSound = false;
                        Toast.makeText(JVSovPlayActivity.this, "关闭声音", Toast.LENGTH_SHORT).show();
                    }

                    SovUtil.disconnect(window);
                    finish();
//                    JVSovPlayActivity.this.finish();
                }
            });
            dialog.show();
            dialog.setContentView(layout);
            dialog.getWindow().clearFlags(
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
                            WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
            dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
            Window window = dialog.getWindow();
            ViewGroup.LayoutParams layoutParams = window.getAttributes();
            WindowManager manager = window.getWindowManager();
            Display display = manager.getDefaultDisplay();
            layoutParams.width = (int) (display.getWidth() * 0.7);
            layoutParams.height = change_campwd_ll.getLayoutParams().height;
            window.setAttributes((WindowManager.LayoutParams) layoutParams);
        }
        /*if (devAdmin && !remind) {
            spf.edit().putBoolean("hasRemind", true).commit();
            //如果判断用户是管理员，提醒修改密码
            new DialogUtil(this, true, true, "为了保障您的隐私安全，请前往\"设置界面\"-\"系统管理\"修改您的摄像机密码", "取消", "设置", new DialogUtil.SureInterfance() {
                @Override
                public void sureTodo() {
                    if (isConnected) {
                        Intent setIntent = new Intent(JVSovPlayActivity.this, JVSovCameraSetActivity.class);
                        setIntent.putExtra("window", window);
                        setIntent.putExtra("yst", devNum);
                        setIntent.putExtra("vpwd", devPwd);
                        JVSovPlayActivity.this.startActivity(setIntent);
                    } else {
                        App.getApp().showToast("视频连接中...");
                    }
                }

                @Override
                public void cancle() {

                }
            }).showCustomDialog();
        }*/
    }

    private int popupWidth;
    private int popupHeight;

    View view;
    int changeStream;
    String nowStream;
    private int effectFlag = 17;

    protected void initUi() {
        setContentView(R.layout.activity_sov_play);
        ((TextView) findViewById(R.id.title_tv)).setText(devNum);

        title_right_img = (ImageView) findViewById(R.id.title_right_img);
        title_right_img.setVisibility(View.VISIBLE);
        title_right_img.setBackgroundResource(R.mipmap.nav_icon_news);
        playSurface = (SurfaceView) findViewById(playsurface);
        linkState = (TextView) findViewById(R.id.linkState);
        landscape_back = (RelativeLayout) findViewById(R.id.landscape_back);
        video_model = (CheckBox) findViewById(R.id.video_model);
        titleview = (RelativeLayout) findViewById(R.id.titleview);

        double_call = (ImageView) findViewById(R.id.double_call);
        open_voice = (ImageView) findViewById(R.id.open_voice);
        change_screen_img = (ImageView) findViewById(R.id.change_screen_img);
        big_microphone_img = (ImageView) findViewById(R.id.big_microphone_img);
        video_cut = (ImageView) findViewById(R.id.video_cut);
        initLandBack();
        initSurfaceView();
        title_right_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (isConnected) {
                    //TODO 修改
                    //消息中心
                    Intent intent = new Intent(JVSovPlayActivity.this, CamMsgActivity.class);
                    intent.putExtra("yst", devNum);
                    intent.putExtra("version", version);
                    startActivity(intent);
//                } else {
//                    App.getApp().showToast("视频连接中...");
//                }
            }
        });
        findViewById(R.id.ll_title_left_view).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (doubleCalling) {
                    stopDoubleCall();
                    Toast.makeText(JVSovPlayActivity.this, "关闭对讲", Toast.LENGTH_SHORT).show();
                }
                if (recording) {
                    JniUtil.stopRecord(window);
                    Toast.makeText(JVSovPlayActivity.this, "停止录像", Toast.LENGTH_SHORT).show();
                    recording = false;
                }
                if (enableSound) {
                    enableSound = false;
                    Toast.makeText(JVSovPlayActivity.this, "关闭声音", Toast.LENGTH_SHORT).show();
                }

                SovUtil.disconnect(window);
                finish();
            }
        });
        findViewById(R.id.video_model).setOnClickListener(new View.OnClickListener() {
                                                              @Override
                                                              public void onClick(View v) {
                                                                  if (isConnected) {
                                                                      if (popupWindow == null) {
                                                                          view = LayoutInflater.from(JVSovPlayActivity.this).inflate(R.layout.pop_lay_stream, null);
                                                                          popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
                                                                          TextView cq = (TextView) view.findViewById(R.id.cq_tv);
                                                                          TextView gq = (TextView) view.findViewById(R.id.gq_tv);
                                                                          TextView lc = (TextView) view.findViewById(R.id.lc_tv);


                                                                          cq.setOnClickListener(new View.OnClickListener() {
                                                                              @Override
                                                                              public void onClick(View v) {
                                                                                  SovUtil.streamCatChangeStream(window, 1);
                                                                                  nowStream = "超清";
                                                                                  video_model.setText("超清");
                                                                                  popupWindow.dismiss();
                                                                              }
                                                                          });
                                                                          gq.setOnClickListener(new View.OnClickListener() {
                                                                              @Override
                                                                              public void onClick(View v) {
                                                                                  SovUtil.streamCatChangeStream(window, 2);
                                                                                  nowStream = "高清";
                                                                                  video_model.setText("高清");
                                                                                  popupWindow.dismiss();
                                                                              }
                                                                          });
                                                                          lc.setOnClickListener(new View.OnClickListener() {
                                                                              @Override
                                                                              public void onClick(View v) {
                                                                                  SovUtil.streamCatChangeStream(window, 3);
                                                                                  nowStream = "流畅";
                                                                                  video_model.setText("流畅");
                                                                                  popupWindow.dismiss();
                                                                              }
                                                                          });
                                                                          popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
                                                                      }
                                                                      popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                                                                          @Override
                                                                          public void onDismiss() {
                                                                              video_model.setChecked(!video_model.isChecked());
                                                                          }
                                                                      });
                                                                      // 设置可以获得焦点
                                                                      popupWindow.setFocusable(true);
                                                                      // 设置弹窗内可点击
                                                                      popupWindow.setTouchable(true);
                                                                      // 设置弹窗外可点击
                                                                      popupWindow.setOutsideTouchable(true);
                                                                      popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
                                                                      popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
                                                                      //获取自身的长宽高
                                                                      view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
                                                                      popupHeight = view.getMeasuredHeight();
                                                                      popupWidth = view.getMeasuredWidth();
                                                                      showUp(video_model);
                                                                  } else {
                                                                      App.getApp().showToast("视频连接中...");
                                                                  }

                                                              }

                                                              public void showUp(View v) {
                                                                  //获取需要在其上方显示的控件的位置信息
                                                                  int[] location = new int[2];
                                                                  v.getLocationOnScreen(location);
                                                                  //在控件上方显示
                                                                  popupWindow.showAtLocation(v, Gravity.NO_GRAVITY, (location[0] + v.getWidth() / 2) - popupWidth / 2, location[1] - popupHeight);
                                                              }
                                                          }
        );

        landscape_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Configuration cf = JVSovPlayActivity.this.getResources().getConfiguration(); //获取设置的配置信息
                int ori = cf.orientation; //获取屏幕方向
                if (ori == cf.ORIENTATION_LANDSCAPE) {
                    //横屏变竖屏
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    landscape_back.setVisibility(View.GONE);
                    titleview.setVisibility(View.VISIBLE);
                    double_call.setVisibility(View.GONE);
                    change_screen_img.setBackgroundResource(R.mipmap.fullscreen_white);

                    ViewGroup.LayoutParams lp = playSurface.getLayoutParams();
                    lp.height = getPixelsFromDp(250);
                    lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
                    playSurface.setLayoutParams(lp);
                    return;
                }
            }
        });
        findViewById(R.id.rollback_video).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isConnected) {
                    /**
                     * 翻转画面
                     */
                    SovUtil.streamRotateVideo(window,
                            CloudUtil.getVideoDirection(effectFlag), effectFlag);
                    if (effectFlag == 17) {
                        effectFlag = 23;
                    } else {
                        effectFlag = 17;
                    }
                } else {
                    App.getApp().showToast("视频连接中...");
                }
            }
        });

    }


    public void initLandBack() {
        Configuration cf = JVSovPlayActivity.this.getResources().getConfiguration(); //获取设置的配置信息
        int ori = cf.orientation; //获取屏幕方向
        if (ori == cf.ORIENTATION_LANDSCAPE) {
            //横屏
            landscape_back.setVisibility(View.VISIBLE);
            titleview.setVisibility(View.GONE);
        } else if (ori == cf.ORIENTATION_PORTRAIT) {
            //竖屏
            landscape_back.setVisibility(View.GONE);
            titleview.setVisibility(View.VISIBLE);
        }
    }

    public void initSurfaceView() {
        playSurface = (SurfaceView) findViewById(playsurface);
        surfaceHolder = playSurface.getHolder();
        surfaceHolder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                if (isConnected) {
                    linkState.setVisibility(View.VISIBLE);
                    linkState.setText("视频连接中...");
                    JniUtil.resumeSurface(window, surfaceHolder.getSurface());
                } else {
                    linkState.setText("视频连接中...");
                    int result = SovUtil.connect(group, ystNo, devUser, devPwd, surfaceHolder.getSurface());
                    if (result > 0) {
                        linkState.setText("正在连接");
                    } else {
                        linkState.setText("连接失败");
                    }
                }
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {

            }
        });
    }

    @Override
    protected void saveSettings() {

    }


    @Override
    protected void freeMe() {

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        JniUtil.resumeSurface(window, surfaceHolder.getSurface());
    }

    @Override
    protected void onResume() {
        //        initSurfaceView();
        super.onResume();
    }

    @Override
    protected void onPause() {
        if (isConnected) {
            JniUtil.pauseSurface(window);
        }
        super.onPause();
    }

    @Override
    public void onHandler(int what, int arg1, int arg2, Object obj) {
        switch (what) {
            //连接结果
            case JVNetConst.CALL_CATEYE_CONNECTED: {
                switch (arg2) {
                    //连接成功
                    case JVNetConst.CCONNECTTYPE_CONNOK: {
                        linkState.setText("连接成功，正在接收数据");
                        break;
                    }
                    //连接异常断开
                    case JVNetConst.CCONNECTTYPE_DISCONNE: {
                        isConnected = false;
                        SovUtil.disconnect(window);
                        linkState.setText("连接异常断开,错误码:arg1=" + arg1 + ";arg2=" + arg2);
                        break;
                    }
                    //其他都是连接失败
                    default: {
                        linkState.setText("连接失败");
                        break;
                    }
                    case JVNetConst.SRC_REMOTE_ACCOUNT:
                }
                break;
            }

           /*
            case JVNetConst.CALL_CATEYE_SENDDATA: {
                try {
                    com.alibaba.fastjson.JSONObject root = JSON.parseObject(obj.toString());
                    int nPacketType = root.getInteger(AppConsts.TAG_NPACKETTYPE);
                    int result = root.getInteger(AppConsts.TAG_RESULT);
                    switch (nPacketType) {
                        case JVNetConst.SRC_EX_REMOTE_MODIFY:
                            if (result == 1) {
                                //更新机智云服务器的密码
                                updateCam();
                            } else {
                                makeText(JVSovPlayActivity.this, "密码修改失败,请稍候再试", Toast.LENGTH_LONG).show();
                            }
                            break;
                            if(){

                            }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            }*/

            case JVNetConst.CALL_NORMAL_DATA: {
                linkState.setText("正在缓冲");
                break;
            }
            //视频连接出图
            case JVNetConst.CALL_NEW_PICTURE: {
                isConnected = true;
                linkState.setVisibility(View.GONE);

                //获取所有配置信息
                SovUtil.getStreamCatDataAll(window);
                break;
            }
            //设置协议回调
            case JVNetConst.CALL_CATEYE_SENDDATA: {
                try {
                    JSONObject object = new JSONObject(obj.toString());
                    int nType = object.getInt("nPacketType");
                    int nCmd = object.getInt("nCmd");
                    Log.e(TAG, "nPacketType=" + nType + "；nCmd=" + nCmd + "；obj=" + obj.toString());
                    switch (nCmd) {
                        //配置信息全的回调
                        //3.系统管理，修改管理员密码
                        //TODO
                        case JVNetConst.SRC_REMOTE_ACCOUNT:
                            switch (nType) {
                                case JVNetConst.SRC_EX_REMOTE_MODIFY:
                                    int result = object.getInt("result");
                                    if (result == 1) {
                                        //更新机智云服务器的密码
                                        if (changeCamepwd) {
                                            updateCam();
                                        }
                                    } else {
                                        makeText(JVSovPlayActivity.this, "密码修改失败,请稍候再试", Toast.LENGTH_LONG).show();
                                    }
                                    //TODO
                                    break;
                            }
                            break;
                        case JVNetConst.SRC_PARAM_ALL: {
                            try {
                                String jsonStrAll = obj.toString();
                                String dataStr = object.getString(AppConsts.TAG_DATA);
                                Log.e("CloudSet", "jsonStrAll=" + jsonStrAll);
                                com.alibaba.fastjson.JSONObject allParamObject = com.alibaba.fastjson.JSONObject.parseObject(dataStr);

                                int nChatMode = allParamObject.containsKey(AppConsts.TAG_STREAM_CAT_CHATMODE) ?
                                        allParamObject.getInteger(AppConsts.TAG_STREAM_CAT_CHATMODE) : 2;
                                int ptzSupport = allParamObject.containsKey(AppConsts.TAG_PTZ_SUPPORT) ?
                                        allParamObject.getInteger(AppConsts.TAG_PTZ_SUPPORT) : 1;
                                int ptz_speed = allParamObject.containsKey(AppConsts.TAG_PTZ_SPEED) ?
                                        allParamObject.getInteger(AppConsts.TAG_PTZ_SPEED) : 0;
                                Log.e("CloudSet", "ptzSupport=" + ptzSupport);

                                // 获取当前码流 1：高清 2：标清 3：流畅
                                currentMobileQuality = allParamObject.getInteger(AppConsts.TAG_STREAM_CAT_MOBILEQUALITY);
                                //                                App.getApp().showToast("当前码流==" + currentMobileQuality);
                                if (currentMobileQuality == 1) {
                                    video_model.setText("超清");
                                } else if (currentMobileQuality == 2) {
                                    video_model.setText("高清");
                                } else {
                                    video_model.setText("流畅");
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            break;
                        }
                        //码流切换回调
                        case JVNetConst.SRC_REMOTE_CMD: {
                            int result = object.getInt("result");
                            if (1 == result) {
                                if (nType == JVNetConst.SRC_EX_CMD_GET_STORAGE) {
                                } else {
                                    Toast.makeText(JVSovPlayActivity.this, "已经切换到" + nowStream, Toast.LENGTH_SHORT).show();
                                }
                            }
                            break;
                        }

                        //对讲回调
                        case JVNetConst.SRC_CHAT: {
                            int result = object.getInt("result");
                            if (nType == JVNetConst.SRC_EX_START_CHAT) {//开启对讲
                                if (result == 1) {//成功
                                    //                                    Toast.makeText(JVSovPlayActivity.this, "主控同意对讲了！", Toast.LENGTH_SHORT).show();
                                    Log.e("CATCAT", "开启对讲--成功：主控同意对讲了！开始发送音频");
                                    JniUtil.startRecordSendAudio(window);
                                    //                                    JniUtil.resumeAudio(connectIndex);
                                    doubleCalling = true;
                                } else if (result == 0) {//失败
                                    Log.e("CATCAT", "开启对讲--失败");
                                }
                            } else if (nType == JVNetConst.SRC_EX_STOP_CHAT) {//结束对讲
                                if (result == 1) {//成功
                                    Log.e("CATCAT", "关闭对讲--成功");
                                    //                                    Toast.makeText(JVSovPlayActivity.this, "收到对讲结束回调！", Toast.LENGTH_SHORT).show();
                                    if (doubleCalling) {//正在对讲，停止对讲
                                        Log.e("CATCAT", "正在对讲_结束对讲");
                                    } else {//设备已在其他客户端开启对讲
                                        Log.e("CATCAT", "设备已在其他客户端开启对讲");
                                        JniUtil.closeSound(window);
                                        //                                        Toast.makeText(JVSovPlayActivity.this, "设备已在其他客户端开启对讲！", Toast.LENGTH_SHORT).show();
                                    }
                                    doubleCalling = false;
                                } else if (result == 0) {//失败
                                    Log.e("CATCAT", "关闭对讲--失败");
                                }
                            }
                            break;
                        }
                        default: {
                            break;
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            }
            default:
                break;
        }
    }

    private ProgressDialog progressDialog;

    public void showProgressDialog(String msg) {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
            progressDialog = null;
        }
        progressDialog = new ProgressDialog(this, ProgressDialog.THEME_DEVICE_DEFAULT_LIGHT);
        progressDialog.setMessage(msg);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setCancelable(true);
        try {
            progressDialog.show();
        } catch (WindowManager.BadTokenException exception) {
            exception.printStackTrace();
        }
    }


    /**
     * 取消对话框显示
     */
    public void disMissDialog() {
        try {
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
                progressDialog = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    boolean changeCamepwd = true;

    public void updateCam() {
        showProgressDialog("加载中...");
        boolean standard = spf.getBoolean("standard", false);
        int configure;
        if (standard) {
            configure = 0;
        } else {
            configure = 1;
        }
        RetrofitService service = RetrofitHelper.getInstance(this).getServer();
        Call<FeedBack> call = service.changeCaminfo(devNum, "admin", newpwd, "", "", "", "", configure + "");
        call.enqueue(new Callback<FeedBack>() {
            @Override
            public void onResponse(Call<FeedBack> call, Response<FeedBack> response) {
                if (response != null && response.body() != null) {
                    int code = response.body().getCode();
                    if (code == 0) {
                        devPwd = newpwd;
                        makeText(JVSovPlayActivity.this, "密码修改成功", Toast.LENGTH_LONG).show();
                        MsgCenter.fireNull("changeVideoPwd", "");
                        dialog.dismiss();
                        disMissDialog();
                    } else {
                        //万一机智云后台密码修改失败 需要把摄像机的密码回滚
                        makeText(JVSovPlayActivity.this, "密码修改失败", Toast.LENGTH_LONG).show();
                        SovUtil.modifyStreamUserInfo(window, "admin", devPwd);
                        changeCamepwd = false;
                        dialog.dismiss();
                        disMissDialog();
                    }
                }
            }

            @Override
            public void onFailure(Call<FeedBack> call, Throwable t) {
                disMissDialog();
            }
        });
    }

    private int getPixelsFromDp(int size) {

        DisplayMetrics metrics = new DisplayMetrics();

        getWindowManager().getDefaultDisplay().getMetrics(metrics);

        return (size * metrics.densityDpi) / DisplayMetrics.DENSITY_DEFAULT;

    }

    @Override
    public void onBackPressed() {
        Configuration cf = JVSovPlayActivity.this.getResources().getConfiguration(); //获取设置的配置信息
        int ori = cf.orientation; //获取屏幕方向
        if (ori == cf.ORIENTATION_LANDSCAPE) {
            //横屏变竖屏
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            landscape_back.setVisibility(View.GONE);
            titleview.setVisibility(View.VISIBLE);
            double_call.setVisibility(View.GONE);
            change_screen_img.setBackgroundResource(R.mipmap.fullscreen_white);

            ViewGroup.LayoutParams lp = playSurface.getLayoutParams();
            lp.height = getPixelsFromDp(250);
            lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
            playSurface.setLayoutParams(lp);
            return;
        }
        if (doubleCalling) {
            stopDoubleCall();
            Toast.makeText(this, "关闭对讲", Toast.LENGTH_SHORT).show();
        }
        if (recording) {
            JniUtil.stopRecord(window);
            Toast.makeText(this, "停止录像", Toast.LENGTH_SHORT).show();
            recording = false;
        }
        if (enableSound) {
            enableSound = false;
            Toast.makeText(this, "关闭声音", Toast.LENGTH_SHORT).show();
        }

        SovUtil.disconnect(window);
        super.onBackPressed();
    }

    @Override
    public void onNotify(int what, int arg1, int arg2, Object obj) {
        handler.sendMessage(handler.obtainMessage(what, arg1, arg2, obj));
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    /**************************************
     * 切换功能
     ***********************************************/
    public void change(View view) {
        Configuration cf = JVSovPlayActivity.this.getResources().getConfiguration(); //获取设置的配置信息
        int ori = cf.orientation; //获取屏幕方向
        if (ori == cf.ORIENTATION_PORTRAIT) {
            //横屏
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            landscape_back.setVisibility(View.VISIBLE);
            titleview.setVisibility(View.GONE);//隐藏标题
            double_call.setVisibility(View.VISIBLE);//显示话筒
            if (doubleCalling) {
                double_call.setBackgroundResource(R.mipmap.microphone_white);
            } else {
                double_call.setBackgroundResource(R.mipmap.microphone_white_close);
            }
            change_screen_img.setBackgroundResource(R.mipmap.smallscreen_white);//显示缩小按钮

            ViewGroup.LayoutParams lp = playSurface.getLayoutParams();
            lp.height = ViewGroup.LayoutParams.MATCH_PARENT;
            lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
            playSurface.setLayoutParams(lp);

            double_call.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (isConnected) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            recordAudioPermission();
                        } else {
                            if (HasAudioPermission.isHasPermission(JVSovPlayActivity.this)) {
                                doubleCall();
                            } else {
                                new AppSettingsDialog.Builder(JVSovPlayActivity.this, JVSovPlayActivity.this.getResources().getString(R.string.audio_show))
                                        .setTitle("权限申请")
                                        .setPositiveButton("确认")
                                        .setNegativeButton("取消", null /* click listener */)
                                        .setRequestCode(REQUEST_RECORD_PERM)
                                        .build()
                                        .show();
                            }
                        }
                    } else {
                        App.getApp().showToast("正在连接视频...");
                    }
                }
            });

        } else if (ori == cf.ORIENTATION_LANDSCAPE) {
            //竖屏
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            landscape_back.setVisibility(View.GONE);
            titleview.setVisibility(View.VISIBLE);
            double_call.setVisibility(View.GONE);
            change_screen_img.setBackgroundResource(R.mipmap.fullscreen_white);

            ViewGroup.LayoutParams lp = playSurface.getLayoutParams();
            lp.height = getPixelsFromDp(250);
            lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
            playSurface.setLayoutParams(lp);
        }
    }

    public void back(View view) {
        if (doubleCalling) {
            stopDoubleCall();
            Toast.makeText(this, "关闭对讲", Toast.LENGTH_SHORT).show();
        }
        if (recording) {
            JniUtil.stopRecord(window);
            Toast.makeText(this, "停止录像", Toast.LENGTH_SHORT).show();
            recording = false;
        }
        if (enableSound) {
            enableSound = false;
            Toast.makeText(this, "关闭声音", Toast.LENGTH_SHORT).show();
        }
        SovUtil.disconnect(window);
        finish();
    }

    //是否正在监听
    private boolean enableSound = false;

    /**************************************
     * 基本功能
     ***********************************************/

    //声音按钮
    public void sound(View view) {
        if (!doubleCalling) {
            if (enableSound) {
                enableSound = false;
                Toast.makeText(this, "关闭声音", Toast.LENGTH_SHORT).show();
                JniUtil.closeSound(window);
                open_voice.setBackgroundResource(R.mipmap.sound_white);
            } else {
                enableSound = true;
                Toast.makeText(this, "开启声音", Toast.LENGTH_SHORT).show();
                JniUtil.openSound(window);
                open_voice.setBackgroundResource(R.mipmap.sound_open_white);
            }
        } else {
            App.getApp().showToast("正在双向视频");
        }
    }

    //抓拍按钮
    public void capture(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            capturePerm();
        } else {
            capturePic();
        }
    }

    //是否正在录像
    private boolean recording = false;

    //录像按钮
    public void record(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            recordVideo();
        } else {
            videoRecord();
        }
    }

    //是否正在对讲
    private boolean doubleCalling = false;

    //双向对讲按钮
    public void call(View view) {
        if (!enableSound) {
            if (isConnected) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    recordAudioPermission();
                } else {
                    if (HasAudioPermission.isHasPermission(JVSovPlayActivity.this)) {
                        doubleCall();
                    } else {
                        new AppSettingsDialog.Builder(JVSovPlayActivity.this, JVSovPlayActivity.this.getResources().getString(R.string.audio_show))
                                .setTitle("权限申请")
                                .setPositiveButton("确认")
                                .setNegativeButton("取消", null /* click listener */)
                                .setRequestCode(REQUEST_RECORD_PERM)
                                .build()
                                .show();
                    }
                }
            } else {
                App.getApp().showToast("正在连接视频...");
            }
        } else {
            App.getApp().showToast("正在单向语音");
        }
    }


    /**
     * 请求录音权限码
     */
    public static final int REQUEST_RECORD_PERM = 103;
    /**
     * 请求操作文件夹权限码
     */
    public static final int REQUEST_FILEPIC_PERM = 104;

    /**
     * EsayPermissions接管权限处理逻辑
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @AfterPermissionGranted(REQUEST_RECORD_PERM)
    public void recordAudioPermission() {
        if (EasyPermissions.hasPermissions(JVSovPlayActivity.this, Manifest.permission.RECORD_AUDIO)) {
            // Have permission, do the thing!
            if (HasAudioPermission.isHasPermission(JVSovPlayActivity.this)) {
                doubleCall();
            } else {
                new AppSettingsDialog.Builder(JVSovPlayActivity.this, JVSovPlayActivity.this.getResources().getString(R.string.audio_show))
                        .setTitle("权限申请")
                        .setPositiveButton("确认")
                        .setNegativeButton("取消", null /* click listener */)
                        .setRequestCode(REQUEST_RECORD_PERM)
                        .build()
                        .show();
            }
        } else {
            // Ask for one permission
            EasyPermissions.requestPermissions(this, "需要请求录音权限",
                    REQUEST_RECORD_PERM, Manifest.permission.RECORD_AUDIO);
        }
    }

    @AfterPermissionGranted(REQUEST_FILEPIC_PERM)
    public void capturePerm() {
        if (EasyPermissions.hasPermissions(JVSovPlayActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            // Have permission, do the thing!
            capturePic();
        } else {
            // Ask for one permission
            EasyPermissions.requestPermissions(this, "需要操作文件夹的权限",
                    REQUEST_FILEPIC_PERM, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
    }

    @AfterPermissionGranted(REQUEST_FILE_PERM)
    public void recordVideo() {
        if (EasyPermissions.hasPermissions(JVSovPlayActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            // Have permission, do the thing!
            videoRecord();
        } else {
            // Ask for one permission
            EasyPermissions.requestPermissions(this, "需要操作文件夹的权限",
                    REQUEST_FILE_PERM, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
    }

    public void capturePic() {
        JniUtil.capture(window);
        Toast.makeText(this, "抓拍成功，请前往文件夹中航安居查看\"抓取图片\"", Toast.LENGTH_SHORT).show();
        updateCam(CAPTURE_PATH);
    }

    public void videoRecord() {
        if (recording) {
            video_cut.setBackgroundResource(R.mipmap.videocut_white);
            JniUtil.stopRecord(window);
            Toast.makeText(this, "停止录像，请前往文件夹中航安居查看\"抓取视频\"", Toast.LENGTH_SHORT).show();
            recording = false;
            updateCam(VIDEO_PATH);
        } else {
            video_cut.setBackgroundResource(R.mipmap.video_blue_open);
            JniUtil.startRecord(window);
            Toast.makeText(this, "开启录像", Toast.LENGTH_SHORT).show();
            recording = true;
        }
    }

    public void updateCam(String path) {
        //发广播告诉相册有图片需要更新，这样可以在图册下看到保存的图片了
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File file = new File(path);
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        sendBroadcast(intent);
    }

    public void doubleCall() {
        if (doubleCalling) {
            stopDoubleCall();
            big_microphone_img.setBackgroundResource(R.mipmap.big_microphone_open);
            double_call.setBackgroundResource(R.mipmap.microphone_white_close);
            Toast.makeText(this, "关闭对讲", Toast.LENGTH_SHORT).show();
        } else {
            startDoubleCall();
            big_microphone_img.setBackgroundResource(R.mipmap.big_microphone_close);
            double_call.setBackgroundResource(R.mipmap.microphone_white);
            Toast.makeText(this, "开启对讲", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        switch (requestCode) {
            case REQUEST_RECORD_PERM:
                doubleCall();
                break;
            case REQUEST_FILE_PERM:
                videoRecord();
                break;
            case REQUEST_FILEPIC_PERM:
                capturePic();
                break;
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        switch (requestCode) {
            case REQUEST_RECORD_PERM:
                if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
                    new AppSettingsDialog.Builder(this, JVSovPlayActivity.this.getResources().getString(R.string.audio_show))
                            .setTitle("权限申请")
                            .setPositiveButton("确认")
                            .setNegativeButton("取消", null /* click listener */)
                            .setRequestCode(REQUEST_RECORD_PERM)
                            .build()
                            .show();
                }
                break;
            case REQUEST_FILE_PERM:
                if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
                    new AppSettingsDialog.Builder(this, "当前App需要操作文件夹的权限,需要打开设置页面么?")
                            .setTitle("权限申请")
                            .setPositiveButton("确认")
                            .setNegativeButton("取消", null /* click listener */)
                            .setRequestCode(REQUEST_FILE_PERM)
                            .build()
                            .show();
                }
                break;
            case REQUEST_FILEPIC_PERM:
                if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
                    new AppSettingsDialog.Builder(this, "当前App需要操作文件夹的权限,需要打开设置页面么?")
                            .setTitle("权限申请")
                            .setPositiveButton("确认")
                            .setNegativeButton("取消", null /* click listener */)
                            .setRequestCode(REQUEST_FILE_PERM)
                            .build()
                            .show();
                }
                break;
        }

    }

    //当前码流 1：超清  2：高清  3：流畅
    private int currentMobileQuality = 0;

    //码流切换按钮
    //    public void changeStream(View view) {
    //        Log.e(TAG, "currentMobileQuality:" + currentMobileQuality);
    //        int changeStream = ++currentMobileQuality > 3 ? 1 : currentMobileQuality;
    //        currentMobileQuality = changeStream;
    //        Log.e(TAG, "change To:" + changeStream);
    //        SovUtil.streamCatChangeStream(window, changeStream);
    //    }


    //开启对讲
    public void startDoubleCall() {
        SovUtil.startStreamVoiceCall(window);
        JniUtil.openSound(window);

    }

    //关闭对讲
    public void stopDoubleCall() {
        SovUtil.stopStreamVoiceCall(window);
        JniUtil.stopRecordSendAudio(window);
        JniUtil.closeSound(window);
    }


    /**************************************
     * 摄像机独有功能
     ******************************************/

    //摄像机远程回放功能
    public void cameraRemotePlay(View view) {
        if (isConnected) {
            Intent remoteIntent = new Intent();
            remoteIntent.setClass(JVSovPlayActivity.this, JVRemoteListActivity.class);
            remoteIntent.putExtra("window", window);
            JVSovPlayActivity.this.startActivity(remoteIntent);
        }
    }


    //摄像机设备设置相关功能
    public void cameraDeviceSet(View view) {
        if (isConnected) {
            Intent setIntent = new Intent(JVSovPlayActivity.this, JVSovCameraSetActivity.class);
            setIntent.putExtra("window", window);
            setIntent.putExtra("yst", devNum);
            setIntent.putExtra("vpwd", devPwd);
            setIntent.putExtra("version", version);
            setIntent.putExtra("devAdmin", devAdmin);
            JVSovPlayActivity.this.startActivity(setIntent);
        } else {
            App.getApp().showToast("视频连接中...");
        }
    }

    /***************************************
     * 猫眼独有功能
     *******************************************/

    //查询照片
    public void catImage(View view) {
        Intent fileIntent = new Intent();
        fileIntent.setClass(this, JVCatFileListActivity.class);
        fileIntent.putExtra("mediaKind", 1);
        fileIntent.putExtra("window", window);
        JVSovPlayActivity.this.startActivity(fileIntent);
    }

    //查询视频
    public void catVideo(View view) {
        Intent fileIntent = new Intent();
        fileIntent.setClass(this, JVCatFileListActivity.class);
        fileIntent.putExtra("mediaKind", 2);
        fileIntent.putExtra("window", window);
        JVSovPlayActivity.this.startActivity(fileIntent);
    }
}
